package com.shinhye.elephantsafe.recevier;

import com.shinhye.elephantsafe.R;
import com.shinhye.elephantsafe.service.LocationService;

import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;

public class SmsReceiver extends BroadcastReceiver {
	private final String TAG = "SmsReceiver";
	private SharedPreferences sp;
	private DevicePolicyManager dpm;

	@Override
	public void onReceive(Context context, Intent intent) {
		Object[] pdus = (Object[]) intent.getExtras().get("pdus");
		String[] commands = {
			"#*location*#", "#*alarm*#", "#*wipedata*#", "#*lockscreen*#"
		};
		sp = context.getSharedPreferences("Setting", Context.MODE_PRIVATE);
		
		boolean simchanged = sp.getBoolean("simchanged", false);
		if(!simchanged) {
			Log.i(TAG, "SIM卡变更后短信命令才可启用");
			return;
		}
		boolean runguard = sp.getBoolean("RunGuard", false);
		if(!runguard) {
			Log.i(TAG, "启动防盗保护，短信命令才可启用");
			return;
		}
		
		for(Object pdu : pdus) {
			SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
			String originalAddr = sms.getOriginatingAddress();
			String safenumber = sp.getString("safephone", "");
			
			if(originalAddr.equals(safenumber)) {
				String body = sms.getMessageBody();
				if(commands[0].equals(body)) {
					Log.i(TAG, "追踪位置执行");
					
					Intent service = new Intent(context, LocationService.class);
					context.startService(service);
					
					String location = sp.getString("location", "");
					String text = null;
					if(TextUtils.isEmpty(location)) {
						text = "Can't obtain the location information! Please try again.";
					} else {
						text = "--location information--" + location;
					}
					SmsManager.getDefault().sendTextMessage(safenumber, null, text, null, null);
					
					abortBroadcast();
				} else if(commands[1].equals(body)) {
					Log.i(TAG, "播放报警音乐");
					
					MediaPlayer mp = MediaPlayer.create(context, R.raw.alarm);
					mp.setLooping(true);
					mp.setVolume(1.0f, 1.0f);
					mp.start();
					
					abortBroadcast();
				} else if(commands[2].equals(body)) {
					Log.i(TAG, "清除手机数据");
					//清除手机和SD卡数据！
//					dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
					
					abortBroadcast();
				} else if(commands[3].equals(body)) {
					Log.i(TAG, "手机锁屏");
					
					dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
					dpm.lockNow();
					//设置锁屏密码
//					dpm.resetPassword("shinhye", DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
					
					abortBroadcast();
				}
			}
		}
	}

}
